<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <textarea name="" id="" cols="30" rows="10" class="inpText"></textarea>
  <ul class="search"></ul>
  <div class="handle">
    <button class="talk">话题</button>
    <button class="upload">上传</button>
  </div>
</body>
<script>
  const inpText = document.querySelector('.inpText'),
    search = document.querySelector('.search'),
    talk = document.querySelector('.talk'),
    upload = document.querySelector('.upload');

  // 发请求
  const queryData = function () { }

  const reg = /#([^#\s]*)/;

  let prev = '';

  // 基于事件委托给li绑定事件
  document.addEventListener('click', function (e) {
    let target = e.target, targetTag = target.tagName, parent = target.parentNode;
    if (targetTag === 'Li' && parent === search) {
      inpText.value = inpText.value.replace(reg, `#${target.innerHTML} `);
      prev = target.innerHTML
      //搜索区域消失
      return
    }
    if (targetTag === 'TEXTAREA' && target === inpText) {
      return
    }
    // 剩下的区域让搜索区域消失
  })

  // 文本框输入
  inpText.addEventListener('input', function () {
    let val = inpText.value, match = reg.exec(val);
    match = match ? match[1] : '';
    if (match && match !== prev) {
      search.style.display = 'block'
      prev = match;
      // 发请求
      queryData(match);
      return
    }
    search.style.display = 'none'
  })

  // 插入话题
  talk.addEventListener('click', function () {
    let value = inpText.value;
    if (reg.test(value)) {
      console.log('已经插入过话题了')
      return
    }
    let n, m;
    n = inpText.selectionStart;
    m = inpText.selectionEnd;
    inpText.value = `${val.slice(0, n)}# ${val.slice(m)}`
    inpText.focus();
    inpText.setSelectionRange(n + 1, m + 1);
  });

  // 话题解析
  upload.addEventListener('click', function () {
    let val = inpText.value;
    let match = reg.exec(val);
    match = match ? match[0] : '';
    if (!val.length) return;
    if (match) {

    } else {
      let [left, right] = val.split(match);
      res.push({
        type: 'text',
        value: left
      })
      res.push({
        type: 'talk',
        value: match
      })
      res.push({
        type: 'text',
        value: right.trim()
      })
    }
  });
</script>

</html>